-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
--
-- Create: 2025-5-9
-- Description: management all objects.
local class = require 'mc.class'
local log = require 'mc.logging'
local local_instance = require 'objects.local'
local remote_instance = require 'objects.remote'
local switch_rule_instance = require 'objects.switch_rule'
local const = require 'constants'

local mgmt = class{}

function mgmt:ctor(sigs)
    self.as_local = nil
    self.as_remote_list = {}
    self.switch_rule_list = {}
    self.as_service = nil
    self.sigs = sigs
end

function mgmt:check_register_status()
    if self.as_local and self.as_service then
        log:notice('all object registered, start initialization')
        self.sigs.start:emit()
    end
end

function mgmt:register_as_local(obj)
    log:notice('as local is already registered')
    local object = local_instance.new(obj, self.sigs.restart_service)
    self.as_local = object
    object:initialize()
    self:check_register_status()
end

function mgmt:register_as_remote(obj)
    local name = obj.name
    local remote_obj = remote_instance.new(obj, name, self.sigs.restart_client)
    self.as_remote_list[name] = remote_obj
    remote_obj:initialize()
end

local function check_swith_rule_valid(obj)
    if obj.RuleType > const.SWITCH_RULE_TYPE_NOT_ALLOW then
        return false, 'RuleType'
    elseif obj.Operator > const.SWITCH_RULE_OPERATOR_NOT_EQUAL or obj.Operator < const.SWITCH_RULE_OPERATOR_GREATER then
        return false, 'Operator'
    elseif obj.Direction > const.SWITCH_RULE_DIRECTION_ACTIVE then
        return false, 'Direction'
    end
    return true
end

function mgmt:register_switch_rule(obj)
    -- 检查合法性
    local ok, prop = check_swith_rule_valid(obj)
    if not ok then
        log:error('swtich rule object [%s] register failed by invalid prop [%s]', obj.name, prop)
        return
    end
    local name = obj.name
    local switch_rule_obj = switch_rule_instance.new(obj, self.sigs.failover, name)
    self.switch_rule_list[name] = switch_rule_obj
    switch_rule_obj:initialize()
end

function mgmt:register_as_service(obj)
    self.as_service = obj
    log:notice('as service is already registered')
    self:check_register_status()
end

return mgmt